<template>
  <el-dialog
      :title="props.type == 'add' ? '添加服务' : '修改服务'"
      v-model="state.visible"
      width="400px"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="服务名称" prop="name">
        <el-input type="text" v-model="state.ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="服务封面">
        <el-upload
            :action="uploadImgServer"
            :on-success="handleUrlSuccess"
            list-type="picture"
            :auto-upload="true"
            :show-file-list="false"
        >
          <img v-if="state.ruleForm.cover" :src="state.ruleForm.cover" class="cover" alt="封面"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="服务描述" prop="description">
        <el-input type="text" v-model="state.ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select v-model="state.ruleForm.serviceType" :rules="state.rules" placeholder="请选择服务类型" style="width: 180px">
          <el-option label="上门服务" value="上门服务">
            <div style="display: flex; align-items: center;">
              <el-icon style="position: relative; top: 1px; margin-right: 8px;">
                <House/>
              </el-icon>
              <span>上门服务</span>
            </div>
          </el-option>
          <el-option label="机构服务" value="机构服务">
            <div style="display: flex; align-items: center;">
              <el-icon style="position: relative; top: 1px; margin-right: 8px;">
                <OfficeBuilding/>
              </el-icon>
              <span>机构服务</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {useRoute} from 'vue-router';
import {House, OfficeBuilding, Plus} from '@element-plus/icons-vue';
import {getElderlyServiceById, updateElderlyService, addElderlyService} from '../service/elderlyServiceApi.js';
import {uploadImgServer} from "../store/index.js";
import {ElMessage} from 'element-plus';

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
});

const formRef = ref(null);
const route = useRoute();
const state = reactive({
  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    name: '',
    cover: '',
    description: "",
    serviceType: ""
  },
  rules: {
    name: [
      {required: true, message: '名称不能为空', trigger: ['change']}
    ],
    cover: [
      {required: true, message: '封面地址不能为空', trigger: ['change']}
    ],
    description: [
      {required: true, message: '描述不能为空', trigger: ['change']}
    ],
    serviceType: [
      {required: true, message: '类型不能为空', trigger: ['change']}
    ]
  },
});

// 获取详情
const getDetail = async (id) => {
  const result = await getElderlyServiceById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    name: result.data.name,
    cover: result.data.cover,
    description: result.data.description,
    serviceType: result.data.serviceType
  };
};

// 上传成功
const handleUrlSuccess = (res) => {
  state.ruleForm.cover = res.data; // 更新封面地址
};

// 开启弹窗
const open = (id) => {
  state.visible = true;
  if (id) {
    state.ruleForm.id = id;
    // 如果是有 id 传入，证明是修改模式
    getDetail(id);
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const {level = 1, parent_id = 0} = route.query;
    state.ruleForm = {
      id: '',
      name: '',
      cover: '',
      description: "",
      serviceType: ""
    };
    state.parentId = parent_id;
    state.categoryLevel = level;
  }
};

// 关闭弹窗
const close = () => {
  state.visible = false;
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        // 添加方法
        await addElderlyService(state.ruleForm).then(() => {
          ElMessage.success('添加成功');
          close();
          if (props.reload) props.reload();
        });
      } else {
        // 修改方法
        await updateElderlyService(state.ruleForm).then(() => {
          ElMessage.success('修改成功');
          // 修改完清空一下
          state.ruleForm = {
            id: '',
            name: '',
            cover: '',
            description: "",
            serviceType: ""
          };
          close();
          if (props.reload) props.reload();
        });
      }
    }
  });
};

defineExpose({open, close});
</script>

<style scoped>
.el-upload__tip {
  float: left;
}

.cover {
  border: 1px solid #FFFFFF;
  border-radius: 10px;
  width: 80px;
  height: 80px;
}
</style>
